/*************************************************
 * 
 * Copyright by Bruno Eberhard
 * 
 * Created on 31.07.2005
 *
 *************************************************/
package fightplan.views.tables;

import java.awt.Color;
import java.awt.Component;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.JTree;

import com.jgoodies.binding.value.ValueModel;

import fightplan.bindx.GLinkedListModel;
import fightplan.bindx.GObservableList;
import fightplan.business.Dojo;
import fightplan.business.Tournament;
import fightplan.ui.BeanPropertyListCellRenderer;
import fightplan.ui.GComboBoxModel;

@SuppressWarnings("serial")
public class DojoCellEditor extends DefaultCellEditor {
	private ValueModel tournament;

	public DojoCellEditor(ValueModel tournament, JTable table, boolean unsetAllow) {
		super(createComboBox(tournament, table, unsetAllow));
		this.tournament = tournament;
	}

	@Override
	public Component getTableCellEditorComponent(JTable table, Object object, boolean isSelected, int row, int column) {
		Object value = object != null ? object : "";
		return super.getTableCellEditorComponent(table, value, isSelected, row, column);
	}

	@Override
	public Component getTreeCellEditorComponent(JTree tree, Object object, boolean isSelected, boolean expanded,
			boolean leaf, int row) {
		Object value = object != null ? object : "";
		return super.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);
	}

	private static JComboBox createComboBox(final ValueModel tournament, JTable table, boolean unsetAllow) {
		final JComboBox comboBox = new JComboBox(new GComboBoxModel<Dojo>(getDojos(tournament)));
		tournament.addValueChangeListener(new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent evt) {
				comboBox.setModel(new GComboBoxModel<Dojo>(getDojos(tournament)));
			}
		});
		comboBox.setRenderer(new BeanPropertyListCellRenderer("name"));
		comboBox.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		comboBox.setEditable(false);
		return comboBox;
	}

	private static GObservableList<Dojo> getDojos(ValueModel tournament) {
		Tournament t = (Tournament) tournament.getValue();
		if (t == null)
			return new GLinkedListModel<Dojo>();
		return t.getDojos();
	}

	public Object getCellEditorValue() {
		Tournament t = (Tournament) tournament.getValue();
		Object o = ((JComboBox) getComponent()).getSelectedItem();
		if (o instanceof Dojo) {
			return o;
		} else if (o instanceof String) {
			Dojo dojo = t.getOrCreateDojo((String) o);
			((JComboBox) getComponent()).setModel(new GComboBoxModel<Dojo>(getDojos(tournament)));
			return dojo;
		}
		return null;
	}

}
